package org.sxp.controller;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.sxp.config.GeneratorConfig;
import org.sxp.entity.CodeModel;
import org.sxp.service.SysGeneratorService;
import org.sxp.utils.PageUtils;
import org.sxp.utils.Query;
import org.sxp.utils.R;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * 代码生成器
 *
 *
 */
@Controller
@RequestMapping("/sys/generator")
public class SysGeneratorController {
	@Autowired
	private SysGeneratorService sysGeneratorService;
	@Autowired
	GeneratorConfig generatorConfig;

	@RequestMapping
	public String view(Model model, HttpServletRequest request){
		model.addAttribute("runingDir",(System.getProperty("user.dir").replaceAll("\\\\","/"))+"/xp-pp-admin");
		model.addAttribute("fileDir","/src/main/java/" + generatorConfig.getMainPath().replaceAll("\\.","/")+"/{moduleName}");
		model.addAttribute("resourcesDir","/src/main/resources/");
		model.addAttribute("tablePrefix",generatorConfig.getTablePrefix());
		return "/generator.html";
	}

	/**
	 * 列表
	 */
	@ResponseBody
	@RequestMapping("/list")
	public R list(@RequestParam Map<String, Object> params){
		PageUtils pageUtil = sysGeneratorService.queryList(new Query(params));
		
		return R.ok().put("page", pageUtil);
	}
	
	/**
	 * 生成代码
	 */
	@RequestMapping("/codeZip")
	public void codeZip(CodeModel codeParams, HttpServletResponse response) throws IOException{
		byte[] data = sysGeneratorService.generatorCode(codeParams);
		
		response.reset();  
        response.setHeader("Content-Disposition", "attachment; filename=\"xpboot.zip\"");
        response.addHeader("Content-Length", "" + data.length);  
        response.setContentType("application/octet-stream; charset=UTF-8");  
  
        IOUtils.write(data, response.getOutputStream());  
	}

	/**
	 * 生成代码
	 */
	@PostMapping("/codeDir")
	@ResponseBody
	public R codeDir(@RequestBody CodeModel codeParams, HttpServletResponse response) throws IOException{
		try{
			sysGeneratorService.generatorCode(codeParams);
			return R.ok();
		}catch (Exception e){
			e.printStackTrace();
		}
		return R.error();
	}
}
